import React from 'react';
import { createModalContainer } from '@/components/changeModal';
import {Button, message, Input,Spin} from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import copy from 'copy-to-clipboard';
import moment from 'moment';


class ExtensionComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            editData: {}
        }
    }
    componentWillMount() {
      window.Isoption = false;
    }
    componentDidMount() {
      window.Isoption = true;
        this.requestCouponById();
    }

    convertCanvasToImage=(canvas)=>{
        const image = new Image();
        image.src = canvas.toDataURL("image/png");            //canvas转化为img
        return image;
    }

    // 画图方法
    imageToCanvas =(url1,url2,code,name,data)=>{
        const that = this;
        const time = moment(data.ValidStartTime).format('YYYY-MM-DD')+'~'+moment(data.ValidEndTime).format('YYYY-MM-DD');
        const canvas = document.getElementById("myCanvas");
        const ctx = canvas.getContext("2d");
        const img1 = new Image();
        img1.crossOrigin = "Anonymous";
        img1.src = url1;                     //前面的不解释了，生成个图片
        img1.onload = function(){
            ctx.drawImage(img1, 0, 0,750, 1204);              //当图片加载完成后 赋到画布上 从0 0 开始。
            const img2 = new Image();
             img2.crossOrigin = "Anonymous";
             img2.src = url2;
             img2.onload = function(){
              ctx.save();                            //保存当前画布状态
              ctx.arc(375, 160, 80, 0, 2 * Math.PI);    //剪切操作 将正方形的头像切成圆的
              // 从画布上裁剪出这个圆形
              ctx.clip();                             //进行裁剪
              ctx.drawImage(img2, 295, 80, 160, 160);   //放入img2 在330 90坐标处     大小 88
              ctx.restore();                           //释放画布状态
              ctx.font="30px Arial";
              ctx.textAlign="center";
              ctx.fillStyle ='#FFFFFF';               //前面是设置文字 属性设为居中
              ctx.fillText(`${name}`,375,286);    //文字 这里是写死的 实际中多传个参数就ok
              ctx.restore();
              ctx.font="24px Arial";
              ctx.textAlign="left";
              ctx.fillStyle ='#FFFFFF';
              ctx.fillText(`有效期限: ${time}`,103,640); //时间
              ctx.restore();
              ctx.font="28px Arial";
              ctx.textAlign="left";
              ctx.fillStyle ='#FFFFFF';
              ctx.fillText(`${data.Name}`,360,500); //名称
              ctx.restore();
              ctx.font="24px Arial";
              ctx.textAlign="left";
              ctx.fillStyle ='#FFFFFF';
              ctx.fillText(data.Condition===0?'无使用门槛':`满${data.Condition}可用`,360,540); //门槛
              ctx.restore();
              ctx.font="24px Arial";
              ctx.textAlign="left";
              ctx.fillStyle ='#FFFFFF';
              ctx.fillText('￥',103,530); //￥
              ctx.restore();
              ctx.font="60px Arial";
              ctx.textAlign="left";
              ctx.fillStyle ='#FFFFFF';
              ctx.fillText(`${data.WaiverAmount}`,127,530); //
              const img3 = new Image();
              img3.crossOrigin = "Anonymous";
              img3.src = code;
              img3.onload = function() {
                  ctx.drawImage(img3,255,794,240,240);     //同理加图像
                    ctx.restore();                           //释放画布状态
                    ctx.font="30px Arial";
                    ctx.textAlign="center";
                    ctx.fillStyle ='#424242';
                    ctx.fillText('扫码领取',375,1090);
                    const imgCode = that.convertCanvasToImage(canvas);    //将图片转为base64
                    that.setState({
                        canvasImg: imgCode.getAttribute('src')
                    })
              }
            }
        }

    }

    requestCouponById =() => {
        const { dispatch } = this.props;
        const {oemInfo} = this.props;
        const url1 = oemInfo.cdnUrl + '/' + 'xkdnewyun/systemfile/store/coupon_poster.jpg';//背景图；
        const url2 = oemInfo.cdnUrl + '/' + `${oemInfo.storeLogo}` +'?0999';
        const name = oemInfo.storeName;
        dispatch({
            type: 'marketing/GetCouponById',
            payload: {
                Id: this.props.param.Id
            },
            callBack: {
                success: res => {
                    if(res.Code ===0) {

                        dispatch({
                            type: 'orderPickUp/GetWxCode',
                            callBack: {
                                success: vres=> {
                                    if(vres.Code ===0) {
                                        const code = oemInfo.cdnUrl + '/' + vres.Data.WxCodeUrl +`?${Math.random()*10000}`;
                                        this.setState({
                                            editData: res.Data,
                                            vCode: oemInfo.cdnUrl + '/' + vres.Data.WxCodeUrl
                                        },()=> {
                                            this.imageToCanvas(url1,url2,code,name, res.Data)
                                        })
                                    }
                                },
                                error: vres=> {
                                    message.error(vres.Msg)
                                }
                            }
                        })
                    }
                },
                error: res=> {
                    console.log(res.Msg)
                }
            }
        })
    }

    // 取消
    handleCancel =() => {
        this.props.cancel();
    }

    clickUrl=(url) => {
        if (copy(url)) {
            message.success('复制成功');
          } else {
            message.error('复制失败');
          }
    }

    render() {
        const {editData, canvasImg, vCode} = this.state;
        const {loading} = this.props;
        return (
            <Spin spinning={loading}>
                <div style={{padding: 24}}>
                    {/* <div className={styles.extension}>
                        <Input disabled value={editData.Alias}/>
                        <Button style={{marginLeft: 8}} onClick={()=>this.clickUrl(editData.Alias)}>复制</Button>
                    </div> */}
                    <div className={styles.imgBox}>
                        <img src={canvasImg} width={272} height={436}/>
                    </div>
                    <div style={{textAlign: 'center'}}>
                        <a href={canvasImg} download className={styles.download}>下载海报</a>
                        <a download="" href={vCode} className={styles.download}style={{marginRight:0}}>下载小程序码</a>
                    </div>
                    <canvas id="myCanvas" width="750" height="1204" style={{display: 'none'}}></canvas>
               </div>
            </Spin>
        )
    }
}

const Extension = createModalContainer(
    connect(({marketing, global, loading}) =>({
        marketing,
        oemInfo:global.oemInfo,
        loading: loading.effects['orderPickUp/GetWxCode'],
    }))(ExtensionComponent),
    true,
    true
);

export default Extension;
